#include "utilities.h"

void printError(const char *errorInfo) { // 对应于设置errno类型
  perror(errorInfo);
  exit(EXIT_FAILURE);
}

int setNoblocking(int fd) { //设置fd非阻塞
  int flags = fcntl(fd, F_GETFL);
  int ret = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
  if (ret == -1) {
    printError("setNoblocking error...");
  }
  return fd;
}

//将fd挂载到epoll红黑树
void addFdOnEpollTree(int epollFd, int fd, bool oneShot) {
  epoll_event event;
  event.data.fd = fd;
  if (oneShot) {
    event.events = EPOLLIN | EPOLLET | EPOLLONESHOT;
  } else {
    event.events = EPOLLIN | EPOLLET;
  }
  setNoblocking(fd);
  epoll_ctl(epollFd, EPOLL_CTL_ADD, fd, &event);
}

void show_error(int connfd, const char *info) { //向客户端打印错误
  std::cout << info << std::endl;
  send(connfd, info, strlen(info), 0);
  close(connfd);
}

void modFd(int epollFd, int fd, int ev) { //修改红黑树上监听事件
  epoll_event event;
  event.data.fd = fd;
  event.events = ev | EPOLLET | EPOLLONESHOT | EPOLLRDHUP;
  epoll_ctl(epollFd, EPOLL_CTL_MOD, fd, &event);
}

void rmFd(int epollFd, int fd) { //删除红黑树上的Fd
  epoll_ctl(epollFd, EPOLL_CTL_DEL, fd, nullptr);
  close(fd);
}

void send404(int fd, const char *filename) {
  int openfd = open(filename, O_RDONLY);
  if (openfd < 0) {
    printError("open file error...");
  }
  struct stat stat_buff;
  fstat(openfd, &stat_buff);
  int ret = sendfile(fd, openfd, NULL, stat_buff.st_size);
  if (ret < 0) {
    printError("sendfile error...");
  }
}

const char *get_file_type(const char *name) {
  const char *dot;
  dot = strrchr(name, '.');
  if (dot == NULL)
    return "text/plain; charset=utf-8";
  if (strcmp(dot, ".html") == 0 || strcmp(dot, ".htm") == 0)
    return "text/html; charset=utf-8";
  if (strcmp(dot, ".jpg") == 0 || strcmp(dot, ".jpeg") == 0)
    return "image/jpeg";
  if (strcmp(dot, ".gif") == 0)
    return "image/gif";
  if (strcmp(dot, ".png") == 0)
    return "image/png";
  if (strcmp(dot, ".au") == 0)
    return "audio/basic";
  if (strcmp(dot, ".wav") == 0)
    return "audio/wav";
  if (strcmp(dot, ".avi") == 0)
    return "video/x-msvideo";
  if (strcmp(dot, ".mov") == 0)
    return "image/quicktime";
  if (strcmp(dot, ".mp3") == 0)
    return "audio/mpeg";
  return "text/plain; charset=utf-8";
}